﻿using Newtonsoft.Json;
using rmTest.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProgramTest
{
    public class DeepCopyShow
    {
        public static void Show()
        {
            //测试几种深拷贝方式的性能问题
            Person p1 = new Person { Id = 1, Name = "wjire" };
            Stopwatch sw1 = new Stopwatch();
            sw1.Start();
            for (int i = 0; i < 100000; i++)
            {
                Person p2 = p1.DeepCopyByBinary();
            }
            sw1.Stop();
            Console.WriteLine($"DeepCopyByBinary 共耗时 {sw1.ElapsedMilliseconds} 毫秒");



            Stopwatch sw2 = new Stopwatch();
            sw2.Start();
            for (int i = 0; i < 100000; i++)
            {
                Person p2 = p1.DeepCopyByXml();
            }
            sw2.Stop();
            Console.WriteLine($"DeepCopyByXml 共耗时 {sw2.ElapsedMilliseconds} 毫秒");


            Stopwatch sw3 = new Stopwatch();
            sw3.Start();
            for (int i = 0; i < 100000; i++)
            {
                Person p2 = p1.DeepCopyByReflection();
            }
            sw3.Stop();
            Console.WriteLine($"DeepCopyByReflection 共耗时 {sw3.ElapsedMilliseconds} 毫秒");


            //利用 json.net 实现深拷贝
            Stopwatch sw4 = new Stopwatch();
            sw4.Start();
            for (int i = 0; i < 100000; i++)
            {
                Person p2 = p1.DeepCopyBySerialize<Person, Person>();
            }
            sw4.Stop();
            Console.WriteLine($"Newtonsoft.Json 共耗时 {sw4.ElapsedMilliseconds} 毫秒");

            //利用 Expression 实现深拷贝
            Stopwatch sw5 = new Stopwatch();
            sw5.Start();
            for (int i = 0; i < 100000; i++)
            {
                Person p2 = p1.DeepCopyByExpression<Person, Person>();
            }
            sw5.Stop();
            Console.WriteLine($"Expression 共耗时 {sw5.ElapsedMilliseconds} 毫秒");

            //利用 Expression+cache 实现深拷贝
            Stopwatch sw6 = new Stopwatch();
            sw6.Start();
            for (int i = 0; i < 100000; i++)
            {
                Person p2 = p1.DeepCopyByExpressionCache<Person, Person>();
            }
            sw5.Stop();

            Console.WriteLine($"Expression+Cache 共耗时 {sw6.ElapsedMilliseconds} 毫秒");
        }
    }

    [Serializable]
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
